package controllers;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import model.LoginModel;
import model.SGIClientModel;
import view.LoginGUI;
import view.SGIClientGUI;
import client.SGI;
import client.SGIClient;

public class SGIClientController implements IValidateInput
{
	
	private SGIClientGUI clientView;
	private SGIClientModel clientModel;
	
	public SGIClientController(SGIClientGUI clientView,SGIClientModel clientModel)
	{
		this.clientView = clientView;
		this.clientModel = clientModel;
		clientView.addOKActionListener(new OKListener());
		clientView.addCancelActionListener(new CancelListener());
	}

	@Override
	public boolean validateInput() 
	{
		try
		{
			if(clientView.getHost().equals("") || clientView.getPort()==0)
			{
				clientView.displayWrnMessage("You MUST fill all the fields!!");
				clientView.clearFields();
				return false;
			}
			return true;
		}
		catch (Exception e)
		{
			clientView.displayWrnMessage("Error: Use of elegal charchters");
			return false;
		}
	}

	
	class OKListener implements ActionListener
	{
		@Override
		public void actionPerformed(ActionEvent arg0)
		{
			if(validateInput() == false)
				return;
			try 
			{
				String host = new String (clientView.getHost());
				int port = clientView.getPort();
				
				clientModel.setHost(host);
				clientModel.setPort(port);
				
				SGI.clnt = new SGIClient(host,port);
				
				if(SGI.clnt.isConnected())
				{
					clientView.dispose();
				
					//create a new login controller
					LoginGUI logView = new LoginGUI();
					LoginModel logModel = new LoginModel();
					LoginController logController = new LoginController(logView,logModel);
					SGI.clnt.addObserver(logController);
				}
				else
				{
					clientView.displayWrnMessage("Faild to connect. check IP and port!");
					clientView.clearFields();
				}
				
			} catch (NumberFormatException e) 
			{
				clientView.displayWrnMessage("Faild to connect. check IP and port!");
				clientView.clearFields();
				e.printStackTrace();
			} 
			catch (IOException e) 
			{
				clientView.displayWrnMessage("Connection problem. check IP and Port.");
				e.printStackTrace();
			}
		}
	}
	
	class CancelListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) 
		{
			clientView.dispose();
			System.exit(0);
		}
	}
}
